# coding=utf-8
import time
import os

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class JSEventHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.src_path.endswith('.min.js'):
            if event.src_path.endswith('.js'):
                print(u"正在压缩" + event.src_path)
                os.popen('java -jar yuicompressor-2.4.8.jar {} > {}'.format(event.src_path,
                                                                            event.src_path[:-2] + "min" + ".js"))
                print(u"压缩完成")


class CSSEventHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.src_path.endswith('.min.css'):
            if event.src_path.endswith('.css'):
                print(u"正在压缩" + event.src_path)
                os.popen('java -jar yuicompressor-2.4.8.jar {} > {}'.format(event.src_path,
                                                                            event.src_path[:-3] + "min" + ".css"))
                print(u"压缩完成")


if __name__ == "__main__":
    # path = "/root/PycharmProjects/peiwan-promoter-web/static"
    path = "/root/PycharmProjects/peiwan-admin/static"
    jsEventHandler = JSEventHandler()
    cssEventHandler = CSSEventHandler()
    cssObserver = Observer()
    jsObserver = Observer()
    cssObserver.schedule(cssEventHandler, path, recursive=True)
    cssObserver.start()
    jsObserver.schedule(jsEventHandler, path, recursive=True)
    jsObserver.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        cssObserver.stop()
        jsObserver.stop()
    cssObserver.join()
    jsObserver.join()
